import {AxiosStatic,AxiosRequestConfig,CancelToken} from "axios"

export class AxiosAnti{
  constructor(axios:AxiosStatic){
    this.axios = axios;
  }
  axios:AxiosStatic
  //
  private cache:Map<string,AbortController> = new Map();
  //
  private getKey(config:AxiosRequestConfig){
    const {url,method,params,data} = config;
    let res = '';
    if(url){
      res += url;
    }
    if(method){
      res += method;
    }
    if(params){
      res += JSON.stringify(params)
    }
    if(data){
      res += JSON.stringify(data)
    }
    return res;
  }
  //
  public init(config:AxiosRequestConfig){
    const key = this.getKey(config);
    //
    if(this.cache.has(key)){
      // 终止请求 防抖
      this.cache.get(key)?.abort();
    }
    //
    const controller = new AbortController();
    config.signal = controller.signal
    this.cache.set(key,controller)
  }

  public finish(config:AxiosRequestConfig){
    const key = this.getKey(config);
    if(this.cache.has(key)){
      this.cache.delete(key)
    }
  }

  public error(err:any){
    if (err.name === 'CanceledError') {    
      // 重复请求
      console.warn('====重复请求====',err)
      return true;
    }else{
      return false;
    }
  }
}